<?php
class AnalysisAction extends IntesysAction
{
    function _initialize(){
        parent::_initialize();
		$this -> is_poser = getposManagerList($this->memberInfo['id']);
		$this -> getManagerList = getManagerList();
        $this->dao = D('Member');// 编辑、删除操作需要
    }
    public function chart(){
        //图表数据统计
        //人员 单条
		
        if($this->_param('pos_id')){
            $member=$this->_param('pos_id');
            $member=$member['0'];
        }else{
            $member=session('Lockman');//员工管理页面判断员工id
            if(empty($member)){//session没有确定哪个人
                $member=$this->memberInfo['id'];
            }
        }
        if($this->_param('keywords')){//关键字查找员工
            $foundout=D('Member')->where("site_id = ".__SITEID__." and ( name like '%".$this->_param('keywords')."%' or nickname like '%".$this-> _param('keywords')."%')")->find();
            $member=$foundout['id'];
        }
        //积分类型 单条
        if($this->_param('grade_type')){
            $gradeType=$this->_param('grade_type');
        }else{
            $gradeType=D('Integral_type')->where('site_id = '.__SITEID__)->find();
            $gradeType=$gradeType['id'];
        }
        //积分表单 多条
        if($this->_param('dataform')){
            $dataform=$this->_param('dataform');
            $map['form_id']=array('in',$dataform);
        }
        $end=time();
        if($this->_param('time')=='month'){//monthly sort
            $start=strtotime(date('Y')."-".date('m')."-1");//month start unixtime 2016-10-01 00:00:00
            $map["dateline"]=array('between',array($start,$end));   //periods of time
        }elseif($this->_param('time')=='week'){//weekly sort
            $date=new DateTime();//use the php origin class
            $date->modify('this week');
            $start=strtotime($date->format('Y-m-d 00:00:00'));//week start
            $map["dateline"]=array('between',array($start,$end));   //periods of time
        }elseif($this->_param('time')=='total'){
            $map['dateline']=array('lt',$end);
        }
        
        $map['member_id']=$member;
        $mem=D('Member')->where('id = '.$member)->find();
        $nowperson=!empty($mem['name'])?$mem['name']:$mem['nickname'];
        $map['integraltypeid']=$gradeType;
        $grade_type=D('Integral_type')->where('id = '. $gradeType)->find();
        $this->assign('gradetype',$grade_type['remark']);//积分类型
        $intesy=D('Integralranking')->where($map)->group("FROM_UNIXTIME(`dateline` + 8 * 3600,'%Y-%m-%d')")->field("sum(num) as sum,FROM_UNIXTIME(`dateline` + 8 * 3600,'%Y年%m月%d日') as date")->select();
        //var_dump(D('Integralranking')->getLastSql());exit;
        $intesyarr=array();
        $intesydate=array();
        foreach($intesy as $key => $val){
            $intesyarr[]=intval($val['sum']);//单日分数
            $intesydate[]=$val['date'];//日期
        }
        $this->assign('jsonarr',json_encode($intesyarr));
        $this->assign('jsondate',json_encode($intesydate));
        //monthly sort
        //让时间不对下面的图表起作用
        $map['dateline']=array('lt',$end);
        $monthintesy=D('Integralranking')->where($map)->group("FROM_UNIXTIME(`dateline` + 8 * 3600,'%Y-%m')")->field("sum(num) as sum,FROM_UNIXTIME(`dateline` + 8 * 3600,'%Y年%m月') as date")->select();
        $monthintesyarr=array();
        $monthintesydate=array();
        foreach($monthintesy as $key => $val){
            $monthintesyarr[]=intval($val['sum']);//单日分数
            $monthintesydate[]=$val['date'];//日期
        }
        $this->assign('monthjsonarr',json_encode($monthintesyarr));
        $this->assign('monthjsondate',json_encode($monthintesydate));
        $this->assign('nowperson',$nowperson);
        //查询不同积分类型共计多少分(某用户某种积分来自哪些表)
        $type=D('Integralranking')->alias('i')->join('think_form f on f.id = i.form_id')->where('integraltypeid ='.$gradeType.' and member_id ='.$member)->group('form_id')->field('i.form_id,f.name as fname,sum(num) as sum')->select();
        $typearr=array();
        foreach($type as $k =>$v){
            $value=!empty($v['sum'])?$v['sum']:0;
            $name=!empty($v['fname'])?$v['fname']:'其他';
            $typearr[]= array($name.' ( 共计:'.$value.'分 )', intval($value));
        }
        $this->assign('jsonPie',json_encode($typearr));
        //查找所有积分来源
        $this->taskform = M('Form') -> where(array('site_id' => __SITEID__)) -> select();
        $this->integraltype = M('Integral_type') -> where(array('site_id' => __SITEID__)) -> select();
        session('callbackname', $member);//回调 用户名
        $this->assign('callbackname',session('callbackname'));
        $this->display();
    }
    //显示图表
    public function index()
    {

        //查找所有积分来源
        $map['site_id']=__SITEID__;
        $map['formula']=array('neq','');
        $this->taskform = M('Form') -> where($map) -> select();
        $this->integraltype = M('Integral_type') -> where(array('site_id' => __SITEID__,'typename '=> 'Binte')) -> select();
        //部门范围
        if((D('Member')->where('id = '.$this->memberInfo['id'])->getfield('isadministrator',false))=='1'){
            $deparr=D('Member_position')->where("site_id = ".__SITEID__.' and pid = 0')->field('id,name')->select();
        }else{
            $mydep=D('Member')->where('id ='.$this->memberInfo['id'])->getfield('memberpositionid',false);
            $mdep=array_filter(explode(',',$mydep));
            foreach($mdep as $ke =>$va){
                $deparr[]=array('id'=>$va,'name'=>D('Member_position')->where('id = '.$va)->getfield('name',false));
            }
        }

        $this->assign('deparr',$deparr);
        $this->display();
    }
	
	public function body(){
		$this->integraltype=D('Integral_type')->where('site_id ='.__SITEID__)->field('id,remark,typename')->order('typename desc')->select();
		$this->positionlist = M('Member_position') -> where(array('pid' => 0, 'site_id' => __SITEID__)) -> select();
		if(isset($_GET['pos_id'])){
			$this->positionname = M('Member_position') -> where(array('id' => $_GET['pos_id'], 'site_id' => __SITEID__)) -> getField('name');
		}
		
	    $this -> display();
	}
	public function indexModule(){
		
		$this->totalstaff=D('Member')->where('site_id ='.__SITEID__." and memberpositionid like '%,".$this->_get('pos_id').",%'")->count();
		//部门奖扣分
		
		if($this->_get('pos_id')){
			$this->indexpos=D('Member_position')->where('id = '.$this->_get('pos_id'))->getField('name',false);
			$this->member_name=D('Member_position')->where('id = '.$this->_get('pos_id'))->getField('member_name',false);
		}else{
			if(isset($_GET['member_id'])){
				$member_id = intval($_GET['member_id']);
			}else{
				$member_id = $this->memberInfo['id'];
			}
			
			$this->memberinfom = D('Member')->where('id = '.$member_id)->find();
			$this->indexpos=D('Member')->where('id = '.$member_id)->getField('memberpositionname',false);
		}
		
		$time=time();
		$monthstart=strtotime(date('Y',$time).'-'.date('m',$time)."-1");
		if(date('m',$time)==12){
			$monthend=strtotime(date('Y-m-31 23:59:59',$time));
		}else{
			$monthend=strtotime(date('Y',$time).'-'.(date('m',$time)+1).'-1');
		}
		$post['i.time']=$get['i.time']=array('between',array($monthstart,$monthend));
		$post['i.type_id']=$get['i.type_id']=D('Integral_type')->where("typename = 'Binte' and site_id =".__SITEID__)->getfield('id',false);
		$post['i.site_id']=$get['i.site_id']=__SITEID__;
		$get['i.changenum']=array('gt','0');
		$post['i.changenum']=array('lt','0');
		$this->display();
	}
	public function total(){
		//积分
		if($this->_param('show')=='staff'){
		$memberposition=D('Member')->where('site_id ='.__SITEID__.' and id='.$member_id)->getfield('memberpositionid');
		$mdep=array_values(array_filter(explode(',',$memberposition)));//数组洗牌
		$time=time();
		if($this->_param('time')=='y'){
			$start=strtotime(date('Y',$time)."-1-1");
			$end=strtotime((date('Y',$time)+1)."-1-1");
		}elseif($this->_param('time')=='m'){
			$start=strtotime(date('Y',$time)."-".date('m',$time)."-1");
			if(date('m',$time)==12){
				$end=strtotime(date('Y-m-31 23:59:59',$time));
			}else{
				$end=strtotime(date('Y',$time).'-'.(date('m',$time)+1).'-1');
			}
		}elseif($this->_param('time')=='w'){
			$date=new DateTime();
			$date->modify('this week');
			$start=strtotime($date->format('Y-m-d'));
			$date->modify('this week +6 days');
			$end=strtotime($date->format('Y-m-d'))+23*59*59;
		}else{
			$start=strtotime(date('Y-m-d 00:00:00',$time));
			$end=strtotime(date('Y-m-d 23:59:59',$time));
		}
		$member_id='';
		if($this->_param('target')!=null){
		$member_id=' and member_id = '.$this->param('target').'  ';
			}
		
		
		$map["t.dateline"]=array('between',array($start,$end));
		$map['t.integraltypeid']=D('Integral_type')->where("site_id = ".__SITEID__." and typename = 'Binte' ".$member_id)->getfield('id',false);
		$member=D('Member')->where('site_id ='.__SITEID__)->getfield('id',true);
		
		$map['t.member_id']=array('in', $member);
		
		$all=D('Integralranking')->alias('t')->join('__MEMBER__ as m on m.id = t.member_id')->where($map)->group('t.member_id')->order('sum(num) desc')->field("t.*,sum(t.num) as sum")->select();
		foreach($all as $key =>$value){
			$mp=array_values(array_filter(explode(',',$value['memberpositionid'])));//数组洗牌
			foreach($mp as $k =>$v){
				$pname=D('Member_position')->where('id = '.$v)->getfield('name',false);
				$all[$key]['pname'].="【".$pname."】";
			}
		if($value['member_id']==$this->memberInfo['id']){
				$this->assign('totalgrade',$value['sum']);
				$this->assign('allid',$key+1);
			}
		}
		$member=D('Member')->where('site_id ='.__SITEID__." and memberpositionid like '%,".$mdep[0].",%'")->getfield('id',true);
		$map['t.member_id']=array('in',$member);
		$depart=D('Integralranking')->alias('t')->where($map)->group('t.member_id')->order('sum(num) desc')->select();
		foreach($depart as $k =>$v){
			if($v['member_id']==$this->memberInfo['id']){
				$this->assign('depid',$k+1);
				
			}
		
		}
		$template='1';
	  
		}else if($this->_param('show')=='position'||$this->_param('show')=='site'){
		
		$lwn=new Lwn_gradeAction();
		$total=$lwn->grade();	
    
	    if($template==null){
		$template='2';
		}
		$this->assign('totalgrade',$total['positive']);
		
		$this->assign('allid',$total['minus']);
		
		$this->assign('depid',$total['count']);
		
		
			}
		  $this->assign('lwn_template',$template);		
		$this->display();
	}
	
	
	
	
	
    public function block(){
        if($this->_param('member'))session('Lockman',$this->_param('member'));
        $this->taskform = M('Form') -> where(array('site_id' => __SITEID__)) -> select();//查找所有积分来源
        $this->integraltype = M('Integral_type') -> where(array('site_id' => __SITEID__)) -> select();
        $this->display();
    }
    public function department(){
		$this->integraltype = M('Integral_type') -> where(array('site_id' => __SITEID__)) -> select();
		//dump($type_id);
        //integral sort in one department
        //search member who in one group
        $end=time();
        $this->assign('thisman',$this->memberInfo['id']);
        if($this->_param('starttime')&&empty($_get['endtime'])){//only starttime
            $start=strtotime($this->_param('starttime'));
            $limit["dateline"]=array('gt',$start);
        }elseif($this->_param('endtime')&&empty($_get['starttime'])){
            $end=strtotime($this->_param('endtime'));
            $limit["dateline"]=array('lt',$end);
        }elseif($this->_param('endtime')&&$_get['starttime']){
            $start=strtotime($this->_param('starttime'));
            $end=strtotime($this->_param('endtime'));
            $limit["dateline"]=array('between',array($start,$end));
        }elseif($this->_param('time')=='year'){//yearly sort
            $start=strtotime(date('Y')."-1-1");//year start unixtime 2016-01-01 00:00:00
            $limit["dateline"]=array('between',array($start,$end));   //periods of time
        }elseif($this->_param('time')=='month'){//monthly sort
            $start=strtotime(date('Y')."-".date('m')."-1");//month start unixtime 2016-10-01 00:00:00
            $limit["dateline"]=array('between',array($start,$end));   //periods of time
        }elseif($this->_param('time')=='week'){//weekly sort
            $date=new DateTime();//use the php origin class
            $date->modify('this week');
            $start=strtotime($date->format('Y-m-d 00:00:00'));//week start
            $limit["dateline"]=array('between',array($start,$end));   //periods of time
        }elseif($this->_param('time')=='defined'){//user defined
            $start=strtotime($this->_param('starttime'));
            $end=strtotime($this->_param('endtime'));
            $limit["dateline"]=array('between',array($start,$end));   //periods of time
        }elseif($this->_param('time')=='day'){//daily sort
            $start=strtotime(date('Y-m-d',time()));
            $this->assign('time',$this->_param('time'));
            $limit["dateline"]=array('between',array($start,$end));   //periods of time
        }
        if($this->_param('integral_type')){//积分类型
            $limit['integraltypeid']=array('eq', $this->_param('integral_type'));
        }else{
            $limit['integraltypeid']=D('Integral_type')->where("site_id = ".__SITEID__." and typename = 'Binte' ")->getfield('id',false);
        }
		
		if(isset($_GET['type_id'])){
			$limit["t.formcategory_id"] = array('in', implode(',', $_GET['type_id']));
		}
		
		$limit["t.site_id"] = __SITEID__;
		
		
		if(isset($_GET['pos_id'])){
			$limit["t.memberpositionid"] = array('like', '%,'.$_GET['pos_id'].',%');
		}
		
		if(isset($_GET['member_id'])){
			$limit["t.memberpositionid"] = M('Member') -> where(array('id' => intval($_GET['member_id']), 'site_id' => __SITEID__)) -> getField('memberpositionid');
		}
		
		
		$all = D('Integralranking') -> alias('t') -> Field('t.*,sum(num) as sum') -> group('t.member_id') -> order('sum desc') -> where($limit) -> select();
		//echo D('Integralranking') -> getLastSql();
		import ( 'ORG.Util.Page' );
		$p=new Page(count($all), 5);
		$all = D('Integralranking') -> alias('t') -> Field('t.*,sum(num) as sum') -> group('t.member_id') ->limit($p->firstRow.',
'.$p->listRows) -> order('sum desc') -> where($limit) -> select();
		$this->pages = $p -> show();
		foreach($all as $k => $v){
			$mi = M('Member') -> where(array('id' => $v['member_id'])) -> find();
			$all[$k]['name'] = $mi['name'];
			$all[$k]['img_url'] = $mi['img_url'];
			$all[$k]['nickname'] = $mi['nickname'];
			$all[$k]['pname'] = $mi['memberpositionname'];
		}
		$this->all = $all;
		$this->display();

		
    }

    public function getExcel()
    {
        Vendor('Excel.PHPExcel');
        $excel = new PHPExcel();
        set_time_limit(0);
        /////////////////////////////取出数据/////////////////////
        //integral sort in one department
        //search member who in one group
        if($this->_param('time')=='year'){//yearly sort
            $start=strtotime(date('Y')."-1-1");//year start unixtime 2016-01-01 00:00:00
            $end=time();
            $this->assign('time',$this->_param('time'));
        }elseif($this->_param('time')=='month'){//monthly sort
            $start=strtotime(date('Y')."-".date('m')."-1");//month start unixtime 2016-10-01 00:00:00
            $end=time();
            $this->assign('time',$this->_param('time'));
        }elseif($this->_param('time')=='week'){//weekly sort
            $date=new DateTime();//use the php origin class
            $date->modify('this week');
            $start=strtotime($date->format('Y-m-d 00:00:00'));//week start
            $end=time();
            $this->assign('time',$this->_param('time'));
        }elseif($this->_param('time')=='defined'){//user defined
            $start=strtotime($this->_param('starttime'));
            $end=strtotime($this->_param('endtime'));
            $this->assign('start',$this->_param('starttime'));
            $this->assign('end',$this->_param('endtime'));
            $this->assign('time',$this->_param('time'));
        }elseif($this->_param('time')=='day'){//daily sort
            $start=strtotime(date('Y-m-d',time()));//month start unixtime 2016-10-01 00:00:00
            $end=time();                           //now
            $this->assign('time',$this->_param('time'));
        }else{                                       //default: year
            $start=strtotime(date('Y')."-1-1");//year start unixtime 2016-01-01 00:00:00
            $end=time();
            $this->assign('time',$this->_param('time'));
        }
        $limit["datetime"]=array('between',array($start,$end));   //periods of time
        //var_dump($this->_param('area[]'));
        //如何获取每一个部门的id
        if(in_array(0,$this->_param('area'))){// in company（all departments）
            $member=D('Member')->where('site_id ='.__SITEID__)->getfield('id',true);
            $this->assign('area','0');
        }elseif($this->_param('area')){          //in department
            $area=$this->_param('area');//所有部门 数组
            //$lemon['pid']=array('in',$area);
            $lemon['id']=array('in',$area);
            //$lemon['_logic']='OR';
            $job=D('Member_group')->where($lemon)->getfield('id',true);//job id
            $member=D('Member')->where(array('group_id'=>array('in',$job)))->getfield('id',true);//job member
            $this->assign('area',$area);
        }else{
            $member=D('Member')->where('site_id ='.__SITEID__)->getfield('id',true);
            $this->assign('area','0');
        }
        $limit['member_id']=array('in',$member);   //department(s)
        if(in_array(0,$this->_param('type'))){
            $this->assign('type','0');
        }elseif($this->_param('type')){
            $type=$this->_param('type');
            $limit['form_id']=array('in',$type);
            $this->assign('type',$type);
        }else{
            $this->assign('type','0');
        }
        //form type in event table
        $form = D('Event')->alias('e')->join('left join __FORM__ as f on e.form_id = f.id')->group('e.form_id')->where('f.id > 0')->field('e.form_id as id,f.name as name')->select();
        $this->assign('form',$form);
        //department type
        $detype=D('Member_group')->where('pid = 0 and site_id ='.__SITEID__)->field('title,id')->select();
        $this->assign('detype',$detype);
        $data=D('Event')->alias('a')->join('__MEMBER__ as m on a.member_id =m.id ')->join('think_member_group as g on g.id = m.group_id')->where($limit)->group('member_id')->field('sum(a.integralnumber) as sum,m.nickname as nickname,m.name as name,g.title as job')->order('sum(a.integralnumber) desc')->select();
        ////////////////////////////////////////////////////////
        $letter = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L');
        $tableheader = array('姓名', '职位', '得分');
        $excel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
        $excel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
        $excel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
        for ($i = 0; $i < count($tableheader); $i++) {
            $excel->getActiveSheet()->setCellValue("$letter[$i]1", "$tableheader[$i]");
        }
        for ($i = 2; $i <= count($data) + 1; $i++) {
            $excel->getActiveSheet()->setCellValue('A' . $i, $data[$i - 2]['name']);
            $excel->getActiveSheet()->setCellValue('B' . $i, ' ' . $data[$i - 2]['job']);
            $excel->getActiveSheet()->setCellValue('C' . $i, $data[$i - 2]['sum']);
            $excel->getActiveSheet()->setCellValue('D' . $i, ' ');
        }
        $write = new PHPExcel_Writer_Excel5($excel);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename="部门积分排行.xls"');
        header("Content-Transfer-Encoding:binary");
        $write->save('php://output');
        exit;
    }
    private function getMemberposition(){
        $this->dao = M('Member_position');
        $pid = $this->_post('id') ? $this->_post('id') : 0;
        $map['m.pid'] = $pid;
        $map['m.site_id'] = __SITEID__;
        $ret = array();
        $list = $this->dao -> where($map) ->alias('m') -> select();
        foreach($list as $k => $v){
            //查找层级
            $sub = $this -> dao -> where(array('pid' => $v['id'])) -> count();
            $isParent = false;
            if($sub > 0){
                $isParent = true;
            }
            $data['isParent'] = $isParent;
            $data['id'] = $v['id'];
            $data['name'] = $v['name'].'';
            $ret[] = $data;
        }
        echo json_encode($ret);
    }
    private function getMember(){
        if($this->_post('id')){
            $pid=$this->_post('id');
        }elseif($this->_post('pid')){
            $pid=$this->_post('pid');
        }else{
            $pid=0;
        }
        //$pid = $this->_post('id') ? $this->_post('id') : $this->_post('pid');
        $map['m.pid'] = $pid;
        $map['m.site_id'] = __SITEID__;
        $map['group_id']=array('gt',0);
        $ret = array();
        $list = $this->dao -> where($map) ->alias('m') -> select();
        foreach($list as $k => $v){
            //查找层级
            $sub = $this -> dao -> where(array('pid' => $v['id'])) -> count();
            $isParent=$sub>0?true:false;
            $data['isParent'] = $isParent;
            $data['id'] = $v['id'];
            $data['name'] = $v['name'].'【有'.$sub.'个下级】';
            $data['realname']=$v['name'];
            $ret[] = $data;
        }
        echo json_encode($ret);
    }
    public function membertree(){
        if(IS_POST){
            $this->getMember();
            exit;
        }
        $this->display();
    }
    public function memberpositiontree(){
        if(IS_POST){
            $this->getMemberposition();
            exit;
        }
        $this->display();
    }
    //查看下级会员
    function sindex(){
        $map = 'mm.member_id = '.$this->_get('id');
        $this->id = $this->_get('id');
        $this->getLevelNameList = $this->dao -> getLevelNameList();
        if($this->_get('keywords')){
            $map .= " and (m.nickname like '%".$this->_get('keywords')."%' or m.id = '".$this->_get('keywords')."')";
            $this->keywords = $this->_get('keywords');
        }
        if($this->_get('level')){
            if($this->_get('level') != 'all'){
                $map .= " and (mm.level = '".$this->_get('level')."')";
            }
            $this->level = $this->_get('level');
        }
        $this->initView();
        $db = D('Member_member');
        $db -> _list($this->view, $map);
        $this->display();
    }
    //编辑会员
    public function edit(){
        // 查找所有积分类型
        $this -> inteType = M('Integral_type') -> where(array('site_id' => __SITEID__)) -> select();
        $this->getLevelNameList = $this->dao -> getLevelNameList();
        $this->position_list=D('Member_position')->getList(['site_id'=>__SITEID__]);
        $this->role_list=D('Member_group')-> getList2(0,0,array('site_id'=>__SITEID__));
        $member_role_user = M('Member_role_user')-> where(array('user_id' => $this->_get('id'))) -> select();
        $employee = $this->dao -> where(array('site_id' => __SITEID__, 'id' => $this->_get('id'))) -> find();
        $memberpostionid = trim($employee['memberpostionid'],',');
        $this -> memberpostion = D('Member_position') -> where("site_id = ".__SITEID__. " and id in(".(empty($memberpostionid)?0:$memberpostionid).")") -> select();
        foreach($member_role_user as $k => $v){
            $member_role_userid[] = $v['role_id'];
        }
        $this->member_role_userids = $member_role_userid;
        $this->rule_list=D('Integral_rule')->alias('r')->join('left join __INTEGRAL_RULETYPE__ t on r.type_id = t.id')->where(array('r.site_id'=>__SITEID__,'t.isfix'=>1))->Field('r.*')->select();
        $this->supplierList=M('Supplier')->alias('s')->join('left join __MEMBER_SUPPLIER__ ms ON s.id=ms.supplier_id and ms.member_id='.$this->_get('id')) -> where(array('s.site_id' => __SITEID__)) -> Field('s.*,ms.member_id,ms.supplier_id') -> select();
        if ($this->_get('id')) {
            $map['id'] = array('eq',$this->_get('id'));
            $info = $this->dao->where($map)->find();
            $info['integralconfig'] =  unserialize($info['integralconfig']);
            $this->assign('info', $info);
            $this->display();
        } else {
            $this->error('参数错误');
        }
    }
    //新建会员
    public function add(){
        $this -> inteType = M('Integral_type') -> where(array('site_id' => __SITEID__)) -> select();
        $this->getLevelNameList = $this->dao -> getLevelNameList();
        $this->role_list=D('Member_group')-> getList2(0,0,array('site_id'=>__SITEID__));
        $this->rule_list=D('Integral_rule')->alias('r')->join('left join __INTEGRAL_RULETYPE__ t on r.type_id = t.id')->where(array('r.site_id'=>__SITEID__,'t.isfix'=>1))->Field('r.*')->select();
        parent::add();
    }
    //更新用户信息
    public function update(){
        $member_id = $this->_post('id');
        if($this -> _post('leveldown') == 0){
            M('Member_member') -> where(array('smember_id' => $member_id)) -> data(array('level' => $this->_post('level'))) -> save();
        }
        $_POST['integralconfig'] = serialize($_POST['integralconfig']);
        $_POST['memberpostionid'] = ','.implode(',', $_POST['member_position_id']).',';
        if(trim($_POST['role_id'][0])!=''){$_POST['group_id']=$_POST['role_id'][0];}
        if($member_id){
            if(""!=trim($_POST['password'])){
                $_POST['password']=md5($_POST['password']);
            }else{
                unset($_POST['password']);
            }
            if(isset($_POST['reg_time'])){$_POST['reg_time']=strtotime($_POST['reg_time']);}
            if(isset($_POST['rule_id'])){$_POST['rule_id']=implode(',',$_POST['rule_id']);}
            if(isset($_POST['role_id'])){
                $data1=$_POST;
                //dump($data);exit();
                $role_user=M('Member_role_user');
                $role_user->where(array('user_id'=>$data1['id']))->delete();
                foreach($data1['role_id'] as $k=>$v){
                    $r['user_id']=$data1['id'];
                    $r['role_id']=$v;
                    if(!$role_user->add($r)){
                        $flag=false;
                    }
                }
            }
            $db = D('Member_supplier');
            $db -> where(array('member_id' => $member_id, 'site_id' => __SITEID__)) -> delete();
            //重新写入
            foreach($_POST['supplier_id'] as $k => $v){
                $data['supplier_id'] = $v;
                $data['member_id'] = $member_id;
                $data['site_id'] = __SITEID__;
                $db -> add($data);
            }
        }
        parent::update();
    }
    public function insert(){
        if($jumpUrl == ''){
            $jumpUrl = (session('jumpUrl')&&session('jumpUrl')!='') ? session('jumpUrl') : U('Admin/' . MODULE_NAME . '/index');
        }
        if(isset($_POST)){
            if(!session(C('ADMIN_AUTH_KEY') )){
                $_POST['pid'] = session(C('USER_AUTH_KEY'));
            }
            if(isset($_POST['reg_time'])){$_POST['reg_time']=strtotime($_POST['reg_time']);}
            if(isset($_POST['rule_id'])){$_POST['rule_id']=implode(',',$_POST['rule_id']);}
            $_POST['password']=md5($_POST['password']);
            $createret = $this->dao->create();
            if(!$createret){
                $this->error($this->dao -> getError());exit;
            }
            $id = $this->dao->add();
            if(!$id){
                $this->error($this->dao -> getError());exit;
            }
            $data=$_POST;
            $flag=true;
            $role_user=M('Member_role_user');
            $role_user->where(array('user_id'=>$data['id']))->delete();
            foreach($data['role_id'] as $k=>$v){
                $r['user_id']=$id;
                $r['role_id']=$v;
                if(!$role_user->add($r)){
                    $flag=false;
                }
            }
            if($flag){
                $this->success('添加成功',$jumpUrl);
            }else{
                $this->error('出错了,可能是数据库链接出错,请检查');
            }
            //parent::insert();
        }
    }
    public function sendMsg(){
        //显示发送页面
        if($this->_post('ids')){
            $this->ids = explode(',', $this->_post('ids'));
            $count = 0;
            foreach($this->ids as $v){
                if(sendWXMsg($v, $this->_post('msg'))){
                    $count ++;
                }
            }
            $ret['status'] = 1;
            $ret['info'] = $count;
            $ret['data'] = '';
            echo json_encode($ret);
        }
    }
    //更新父ID
    public function updatePid(){
        if($this->_post('pid')){
            $pid = $this->_post('pid');
            $member_id = $this -> _post('member_id');
            $ret = $this->dao -> updatePid($member_id, $pid);
            if($ret){
                $this->success('操作成功！');
            }else{
                $this->error('操作失败，该会员的父ID不能更改');
            }
        }else{
            $this->error('参数错误');
        }
    }
    //更新父ID
    public function deletePid(){
        if($this->_get('pid')){
            $pid = $this->_get('pid');
            $member_id = $this -> _get('member_id');
            $ret = $this->dao -> deletePid($member_id, $pid);
            if($ret){
                M('Member_member') -> where(array('site_id' => __SITEID__, 'member_id'=>$pid, 'smember_id' => $member_id )) -> delete();
                $this->success('操作成功！');
            }else{
                $this->error('操作失败，该会员的父ID不能更改');
            }
        }else{$this->error('参数错误');}
    }
    public function delete(){
        if(isset($_GET['id']) && intval($_GET['id'])>0){
            M('Member_member') -> where(array('site_id' => __SITEID__, 'smember_id' => $this->_get('id') )) -> delete();
        }
        parent::delete();
    }
    //添加会员积分
    public function addintegral(){
        $id = $this->_get('id');
        if(IS_POST){
            $id = $this->_post('id');
            $integral = $this->_post('integral');
            import("@.ORG.Integrals.Integral");
            $Integral = new Integral($id);
            $mes = $Integral->giveIntegral($integral);
            if($mes){
                $this->success('操作成功！');
                exit;
            }else{
                $this->error('操作失败');
                exit;
            }
        }
        $this->assign('id',$id);
        $this->display();
    }
    //会员直接登录
    public function login(){
        $member = $this->dao -> where(array('site_id' => __SITEID__, 'id' => $this-> _get('id'))) -> find();dump($member);
        session('memberInfo', $member);
        redirect('/'.__SITEID__.U('Member/Index/index'));
    }
    //选择列表
    public function select(){
        $this->pagesize = 12;
        $this->listmap = "site_id = ". __SITEID__;
        $this->listmap .= " and group_id <> 0 ";
        if($this->_get('selected') && $this->_get('selected') != ''){
            $this->pagesize = 100;
            $this->listmap = "id in(".$this->_get('selected').")";
        }
        if($this->_param('keywords')){
            $keywords=$this->_param('keywords');
            $_GET['keywords']=urlencode($this->_param('keywords'));
            $this->listmap.=" and title like '%{$keywords}%'";
            $this->keywords=$keywords;
        }
        parent::_list();
        $list = $_GET['list'];
        $statu=$list?1:0;
        if(IS_AJAX){
            die(json_encode(array('tbody'=>$this->fetch(),'dump'=>$_REQUEST,'statu'=>$statu, 'pages' => $this->get('pages'))));
        }else{
            $this->display();
        }
    }
    //查看排名 (首页积分排名及积分异常提醒)
    public function ranking(){
        $pid=$this->memberInfo['id'];
        $member=$this->dao->where('pid = '.$pid)->select();
        foreach($member as $key => $val){
            $special=D('Integralranking')->where('member_id = '.$val['id'])->group("FROM_UNIXTIME(`dateline` + 8 * 3600,'%Y-%m')")->field("sum(num) as sum,FROM_UNIXTIME(`dateline` + 8 * 3600,'%Y年%m月') as date")->select();
            $special=array_slice($special,'-2');
            if(count($special)==2){//至少有两个月的积分才能比较
                $rate[$val['id']]=$special['1']['sum']/$special['0']['sum'];
            }
        }
        arsort($rate);//键值倒序
        //var_dump($rate);exit; //1.24   1.14
        if(current(array_values($rate))>=1.20){//rate>4/3 正变动最大且大于4/3 上升异常
            $up_member=current(array_keys($rate));//member_id
            $up_rate=current(array_values($rate));//
        }
        if(end(array_values($rate))<=1.15){//rate<3/4 负変动最大  下滑异常
            $down_member=end(array_keys($rate));
            $down_rate=end(array_values($rate));
        }
        if(!empty($up_rate)){//有上升异常
            $up_detail=D('Integralranking')->where('member_id = '.$up_member)->group("FROM_UNIXTIME(`dateline` + 8 * 3600,'%Y-%m')")->field("sum(num) as sum,FROM_UNIXTIME(`dateline` + 8 * 3600,'%Y年%m月') as date")->select();
            $up_arr=array();
            $up_date=array();
            foreach($up_detail as $key => $val){
                $up_arr[]=intval($val['sum']);//单日分数
                $up_date[]=$val['date'];//日期
            }
            $this->assign('up_arr',json_encode($up_arr));
            $this->assign('up_date',json_encode($up_date));
            $up=D('Member')->where('id ='.$up_member)->find();
            $this->assign('up_member',$up_member);
            $this->assign('up_person',$up['name']);
        }
        if(!empty($down_rate)){//有下降异常
            $down_detail=D('Integralranking')->where('member_id = '.$down_member)->group("FROM_UNIXTIME(`dateline` + 8 * 3600,'%Y-%m')")->field("sum(num) as sum,FROM_UNIXTIME(`dateline` + 8 * 3600,'%Y年%m月') as date")->select();
            $down_arr=array();
            $down_date=array();
            foreach($down_detail as $key => $val){
                $down_arr[]=intval($val['sum']);//单日分数
                $down_date[]=$val['date'];//日期
            }
            $this->assign('down_arr',json_encode($down_arr));
            $this->assign('down_date',json_encode($down_date));
            $down=D('Member')->where('id ='.$down_member)->find();
            $this->assign('down_member',$down_member);
            $this->assign('down_person',$down['name']);
        }
        $this->display();
    }
    private function year($time){
        $time=$time?$time:time();
        $year['start']=strtotime(date('Y',$time)."-1-1");//year start unixtime 2016-01-01 00:00:00
        $year['end']=strtotime((date('Y',$time)+1).'-1-1');
        return $year;
    }
    private function month($time){
        $time=$time?$time:time();
        $month['start']=strtotime(date('Y',$time).'-'.date('m',$time)."-1");
        if(date('m',$time)==12){
            $month['end']=strtotime(date('Y-m-31 23:59:59',$time));
        }else{
            $month['end']=strtotime(date('Y',$time).'-'.(date('m',$time)+1).'-1');
        }
        return $month;
    }
    private function yearlist($mid,$gradetype,$start,$end){
        $map['member_id']=$mid;
        $map['dateline']=array('between',array($start,$end));
        $yearlist=D('Integralranking')->where($map)->group("FROM_UNIXTIME(`dateline` + 8 * 3600,'%Y-%m')")->field("sum(num) as sum,FROM_UNIXTIME(`dateline` + 8 * 3600,'%Y年%m月') as date")->select();
        $yeararr=array();
        $yeardate=array();
        foreach($yearlist as $key => $val){
            $yeararr[]=intval($val['sum']);//单日分数
            $yeardate[]=$val['date'];//日期
        }
        $tip['i.member_id']=$mid;
        $tip['i.integraltypeid']=$gradetype;
        $tip["i.dateline"]=$map['dateline'];   //periods of time
        $yearsql=D('Integralranking')->alias('i')->join('__FORM__ f on f.id = i.form_id')->join('right join __FORMCATEGORY__ c on c.id =f.topid')->where($tip)->group('f.topid')->field('c.name as formname,sum(i.num) as  sum')->select();
        $arr=array();
        foreach($yearsql as $key => $val){
            $arr[]=array('name'=>$val['formname'],'y'=>intval($val['sum']));
        }
        $yearreturn['yearform'] =json_encode($arr);
        $yearreturn['arr']      =json_encode($yeararr);
        $yearreturn['date']     =json_encode($yeardate);
        return $yearreturn;
    }
    private function monthlist($mid,$gradetype,$start,$end,$map=[]){
		$map=$map;
        $map['member_id']=$mid;
        $map["dateline"]=array('between',array($start,$end));   //periods of time
        $monthlist=D('Integralranking')->where($map)->group("FROM_UNIXTIME(`dateline` + 8 * 3600,'%Y-%m-%d')")->field("sum(num) as sum,FROM_UNIXTIME(`dateline` + 8 * 3600,'%Y年%m月%d日') as date")->select();
        $montharr=array();
        $monthdate=array();
        foreach($monthlist as $key => $val){
            $montharr[]=intval($val['sum']);//单日分数
            $monthdate[]=$val['date'];//日期
        }
        $tip['i.member_id']=$mid;
        $tip['i.integraltypeid']=$gradetype;
        $tip["i.dateline"]=$map["dateline"];   //periods of time
        $monthsql=D('Integralranking')->alias('i')->join('__FORM__ f on f.id = i.form_id')->join('right join __FORMCATEGORY__ c on c.id =f.topid')->where($tip)->group('f.topid')->field('c.name as formname,sum(i.num) as  sum')->select();
        $newarr=array();
        foreach($monthsql as $k => $v){
            $newarr[]=array('name'=>$v['formname'],'y'=>intval($v['sum']));
        }
        $monthreturn['monthform'] =json_encode($newarr);
        $monthreturn['arr']=json_encode($montharr);
        $monthreturn['date']=json_encode($monthdate);
        return $monthreturn;
    }
    private function weeklist($mid,$start,$end){
        $map["dateline"]=array('between',array($start,$end));
        $map['member_id']=$mid;
        $weeklist=D('Integralranking')->where($map)->group("FROM_UNIXTIME(`dateline` + 8 * 3600,'%v')")->field("sum(num) as sum,FROM_UNIXTIME(`dateline` + 8 * 3600,'%v') as date")->select();
        $weekarr=array();
        $weekdate=array();
        foreach($weeklist as $key => $val){
            $weekarr[]=intval($val['sum']);//单日分数
            $year = date('Y',$start);
            $week = $val['date'];
            $weeks['mon']=strtotime($year.'-W'.$week.'-0')<$start   ? date('m-d',$start):date('m-d',strtotime($year.'-W'.$week.'-0'));
            $weeks['sun']=strtotime($year.'-W'.$week.'-6')>$end     ? date('m-d',$end)  :date('m-d',strtotime($year.'-W'.$week.'-6'));
            $weekdate[]=$weeks['mon'].'至'.$weeks['sun'];//周日至周六
        }
        $weekreturn['arr']=json_encode($weekarr);
        $weekreturn['date']=json_encode($weekdate);
        return $weekreturn;
    }
    public function chartlist(){
        //type
        $gradetype=D('Integral_type')->where("typename = 'Binte' ")->getfield('id',false);//获取B分的id
        //time y-m-d string
        $time=$this->_param('time')?strtotime($this->_param('time')):time();
        $monthstart=$this->month($time)['start'];
        $monthend=$this->month($time)['end'];
        $position=D('Member_position')->where('site_id ='.__SITEID__)->field('member_id')->select();
        $posarr=array();
        foreach($position as $key =>$val){//生成所有管理层
            $temparr=explode(',',$val['member_id']);
            foreach($temparr as $k =>$v){
                if(!in_array($v,$posarr)&&!empty($v))
                    array_push($posarr,$v);
            }
        }
        if(in_array($this->memberInfo['id'],$posarr)){//判断是否为中间层级的管理者
            $station=D('Member_position')->where("member_id like '%".$this->memberInfo['id']."%' ")->getfield('id',false);
            $membertype=1;
        }else{
            $membertype=0;
        }
        if($this->_param('member_pos_id')){//查部门
            $posid=$this->_param('member_pos_id');
        }elseif($this->_param('member_member_id')){//查个人
            $memberid=$this->_param('member_member_id');
        }else{                                     //查自己
            $memberid=$this->memberInfo['id'];
        }
        //1.老板boss
        if((D('Member')->where('id = '.$this->memberInfo['id'])->getfield('isadministrator',false))=='1'){
            $this->assign('isadmin','1');
            //1-1经理的奖扣分对比
            if(empty($posid)&&empty($memberid)||(isset($posid)&&D('Member_position')->where('id = '.$posid.' and site_id ='.__SITEID__)->getfield('pid',false)==0)){//1-1-1 无部门无个人(或者选择了职位总分类(pid=0，例如:总经办))
                //1-1-1-1 经理级的奖扣分对比情况
                $this->assign('poccess','1');
                $post['i.time']=$get['i.time']=array('between',array($monthstart,$monthend));
                $post['i.type_id']=$get['i.type_id']=$gradetype;
                $post['i.site_id']=$get['i.site_id']=__SITEID__;
                $get['i.changenum']=array('gt','0');
                $post['i.changenum']=array('lt','0');
                $getsql=D('Integral_log')->alias('i')->join('right join __MEMBER__ m on m.id = i.giver_id')->where($get)->group('i.giver_id')->getfield('m.name as name,sum(i.changenum) as sum');
                $postsql=D('Integral_log')->alias('i')->join('right join __MEMBER__ m on m.id = i.giver_id')->where($post)->group('i.giver_id')->getfield('m.name as name,sum(i.changenum) as sum');
                foreach($getsql as $k =>$v){
                    $addarr[$k]=intval($v);
                    $dearr[$k]=0;
                }
                foreach($postsql as $ke =>$ve){
                    $dearr[$ke]=abs(intval($ve));
                    if (!array_key_exists($ke,$addarr))$addarr[$ke]=0;
                }
                $this->assign('dname',json_encode(array_keys($addarr)));//奖扣分人
                $this->assign('addval',json_encode(array_values($addarr)));//加分
                $this->assign('cutval',json_encode(array_values($dearr)));//减分
                //1-1-1-2 部门的总积分对比情况
                $depart=D('Integralranking')->alias('i')->join('__MEMBER__ m on m.id= i.member_id')->join('right join __MEMBER_POSITION__ p on p.id =m.position_id')->where('i.site_id ='.__SITEID__)->group('m.position_id')->field('sum(i.num) as sum,p.name as pname')->select();
                foreach($depart as $ky =>$vl){
                    $dename[]=$vl['pname'];
                    $devalue[]=intval($vl['sum']);
                }
                $this->assign('dename',json_encode($dename));//部门
                $this->assign('devalue',json_encode($devalue));//分数
            }elseif($posid){//1-1-2 选择部门
                $this->assign('poccess','2');
                $thisman=D('Member_position')->where('id = '.$posid)->find();
                $this->assign('thisman',$thisman['member_name']);
                $this->manager($posid,$gradetype,$time);
            }elseif($memberid){// 1-1-3 选择了具体的人，显示个人年月周积分情况
                $this->staff($memberid,$gradetype,$time);
                $this->assign('thisman',D('Member')->where('id = '.$memberid)->getfield('name',false));
                $this->assign('poccess','3');
            }
        }elseif($membertype==1){//2. 管理层
            $this->assign('leader',1);
            if(empty($memberid)){
                $this->assign('poccess','4');
                $posid=$station;
                $this->manager($posid,$gradetype,$time);
            }else{
                $this->assign('poccess',5);
                $this->assign('thisman',D('Member')->where('id = '.$memberid)->getfield('name',false));
                $this->staff($memberid,$gradetype,$time);
            }
        }else{//3. 普通员工
            $this->assign('staff',1);
            $this->assign('thisman',D('Member')->where('id = '.$memberid)->getfield('name',false));
            $this->staff($memberid,$gradetype,$time);
        }
        $this->display();
    }
    //普通员工 
    public function staff($memberid,$gradetype,$time){
        $yearstart=$this->year($time)['start'];
        $yearend=$this->year($time)['end'];
        $monthstart=$this->month($time)['start'];
        $monthend=$this->month($time)['end'];
        //yearlist
        $yearlist=$this->yearlist($memberid,$gradetype,$yearstart,$yearend);
        $this->assign('yeararr',$yearlist['arr']);
        $this->assign('yeardate',$yearlist['date']);
        $this->assign('yearform',$yearlist['yearform']);
        //monthlist
        $monthlist=$this->monthlist($memberid,$gradetype,$monthstart,$monthend);
        $this->assign('montharr',$monthlist['arr']);
        $this->assign('monthdate',$monthlist['date']);
        $this->assign('monthform',$monthlist['monthform']);
        //weeklist
        $weeklist=$this->weeklist($memberid,$monthstart,$monthend);
        $this->assign('weekarr',$weeklist['arr']);
        $this->assign('weekdate',$weeklist['date']);
        $this->assign('yearly','个人积分情况（'.date('Y年',$time).'）');
        $this->assign('monthly','个人积分情况（'.date('Y年m月',$time).'）');
    }
    private function manager($posid,$gradetype,$time){
        $start=$this->month($time)['start'];
        $end=$this->month($time)['end'];
        //1-1-2-1 经理的奖扣分情况（奖扣分情况折线图，奖扣分对比的饼图，已奖应奖已扣应扣对比图的饼图）
        $manager=D('Member_position')->where('id ='.$posid)->find();
        $awardmap=array('i.giver_id'=>$manager['member_id'],'i.time'=>array('between',array($start,$end)),'i.type_id'=>$gradetype,'i.site_id'=>__SITEID__,'i.changenum'=>array('gt','0'));
        $deductmap=array('i.giver_id'=>$manager['member_id'],'i.time'=>array('between',array($start,$end)),'i.type_id'=>$gradetype,'i.site_id'=>__SITEID__,'i.changenum'=>array('lt','0'));
        $award=D('Integral_log')->alias('i')->where($awardmap)->join('right join __MEMBER__ m on m.id = i.giver_id')->field('i.*,sum(i.changenum) as award')->find();//该月已奖总积分
        $award=$award['award']?intval($award['award']):0;
        $deduct=D('Integral_log')->alias('i')->where($deductmap)->join('right join __MEMBER__ m on m.id = i.giver_id')->field('i.*,-sum(i.changenum) as deduct')->find();//该月已扣总积分
        $deduct=$deduct['deduct']?intval($deduct['deduct']):0;
        $record=array(array('已奖积分 '.$award.'分',$award),array('已扣积分 '.$deduct.'分',$deduct));
        $this->assign('record',json_encode($record));
        $this->assign('award',$award);
        $this->assign('deduct',$deduct);
        $awardlist=D('Integral_log')->alias('i')->where($awardmap)->join('right join __MEMBER__ m on m.id = i.giver_id')->group("FROM_UNIXTIME(`time` + 8 * 3600,'%Y-%m-%d')")->field("sum(changenum) as sum,FROM_UNIXTIME(`time` + 8 * 3600,'%Y年%m月%d日') as date")->select();//该月已奖积分详情
        foreach($awardlist as $k => $v){
            $awarddate[]=$v['date'];
            $awardsum[]=intval($v['sum']);
        }
        $this->assign('awarddate',json_encode($awarddate));
        $this->assign('awardsum',json_encode($awardsum));
        $deductlist=D('Integral_log')->alias('i')->where($deductmap)->join('right join __MEMBER__ m on m.id = i.giver_id')->group("FROM_UNIXTIME(`time` + 8 * 3600,'%Y-%m-%d')")->field("sum(changenum) as desum,FROM_UNIXTIME(`time` + 8 * 3600,'%Y年%m月%d日') as dedate")->select();//该月已扣积分详情
        foreach($deductlist as $ke => $ve){
            $deductdate[]=$ve['dedate'];
            $deductsum[]=intval(abs($ve['desum']));
        }
        $this->assign('deductdate',json_encode($deductdate));
        $this->assign('deductsum',json_encode($deductsum));
        $showconfig=D('Member')->where('id ='.$manager['member_id'])->find();
        $inte=unserialize($showconfig['integralconfig']);
        $this->Binte=$inte['Binte'];
        $this->awardinlaw= $this->Binte['0']?$this->Binte['0']:0;//奖分权限（应奖）
        $this->deductinlaw= $this->Binte['1']?$this->Binte['0']:0;//扣分权限（应扣）
        $this->assign('manager',$manager['member_name']);//奖扣分人（经理）
        //1-1-2-2 部门各员工积分情况
        $depart=D('Integralranking')->alias('i')->join('__MEMBER__ m on m.id= i.member_id and m.site_id ='.__SITEID__." and m.memberpositionid = ',".$posid.",'")->where('i.site_id ='.__SITEID__." and  m.id= i.member_id and i.memberpositionid =',".$posid.",' and i.dateline between ".$start." and ".$end)->group('i.member_id')->field('sum(i.num) as sum,m.name as name,m.id as id ')->select();
        foreach($depart as $ky =>$vl){
            $depname[]=$vl['name'];
            $depvalue[]=intval($vl['sum']);
        }
        $this->assign('depname',json_encode($depname));//部门人员
        $this->assign('depvalue',json_encode($depvalue));//分数
    }
    //查找所有符合条件的子分类
    public function subtree($sql,$pid = 0, $level = 0){
        static  $arrTree = array(); //使用static代替global
        if( empty($sql)) return FALSE;
        $level++;
        foreach($sql as $key => $value)
        {
            if($value['id']==$pid){
                $arrTree[] = $value['id'];
            }elseif($value['pid'] == $pid){
                $value['level'] = $level;
                $arrTree[] = $value['id'];
                unset($sql[$key]); //注销当前节点数据，减少已无用的遍历
                $this->subtree($sql, $value['id'], $level);
            }
        }
        return $arrTree;
    }
	
	
	
	 public function exportIntesys()
    {
		
        $date=$this->_param('time');
  	    $target=$this->_param('target'); 
		$area=$this->_param('area');
        $member = M('Member'); 
        $integral=M('Integralranking');
		$user = array();
       
	    $lt=new Lwn_gradeAction();
		$time=$lt->l_time($date);
	
		if($area=='position'){
		$where='site_id = '.__SITEID__.'   and dateline > '.$time['start_time'].' and dateline < '.$time['out_time'];
		
		$allMember=$member->where('site_id = '.__SITEID__.' and  group_id = '.$target)->field('id,name,memberpositionname,group_id')->select();
		}else{
		$where='site_id = '.__SITEID__.'  and dateline > '.$time['start_time'].' and dateline < '.$time['out_time'];	
		$allMember=$member->where('site_id = '.__SITEID__)->field('id,name,memberpositionname,group_id')->select();	
		}
		
		
		 
        foreach($allMember as $mkey => $mval){
			$user[$mkey]['name']=$mval['name'];
			$user[$mkey]['memberpositionname']=$mval['memberpositionname'];
			
            $p_num=$integral->where($where.' and num > 0  and member_id = '.$mval['id'])->getField('sum(num)');
		
			if(!$p_num){
				
			unset($p_num);
			$p_num=0;	
			
				}
			
			$user[$mkey]['p_num']=$p_num;
			
			$n_num=$integral->where($where.' and num < 0 and member_id = '.$mval['id'])->getField('sum(num)');
			if(!$n_num){
			$n_num=0;	
				}
			$user[$mkey]['n_num']=$n_num;
			
			$sum=$integral->where($where.' and member_id = '.$mval['id'])->getField('sum(num)');
			if(!$sum){
			$sum=0;	
				}			
			$user[$mkey]['sum']=$sum;
			
			
			
			
			
			}
     
        $xlsTitle = "Member";
        
        $Cell = array(
            array(
                "name",
                "姓名"
            ),
			array(
			    "p_num",
			    "加分"
			),
			array(
				"n_num",
			    "扣分"
			),
            array(
                "sum",
                "总分"
            ),
            array(
                "memberpositionname",
                "部门"
            ),
			array(
			    "rank",
			    "排名"
			),
        );
        
		
		foreach($user as $i => $uval){
		   	 $tmp=array();
			for($j=0;$j<count($user);$j++){
				
			if($user[$i]['sum']>$user[$j]['sum']||$user[$i]==NULL){
				$tmp=$user[$i];
				$user[$i]=$user[$j];
				$user[$j]=$tmp;
				}
		
		
			}
					
			
			}
			
		for($i=0;$i<count($user);$i++){
			$user[$i]['rank']=$i+1;
			}

		
       $this->exportExcel($xlsTitle, $Cell, $user);
    }
	
	 	
	
	  // 导出到Excel
    public function exportExcel($expTitle, $expCellName, $expTableData)
    {
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle); // 文件名称 UTF-8有可能乱码所以转成gb
        $fileName = $_SESSION['account'] . date('_YmdHis'); // 文件名，用时间命名
        
        $cellNum = count($expCellName); // 表头
        
        $dataNum = count($expTableData); // 数据
        
        Vendor("PHPExcel.Classes.PHPExcel");
        Vendor("PHPExcel.Classes.PHPExcel.IOFactory"); // 导入PHPExcel库
        
        $objPHPExcel = new PHPExcel();
        $cellName = array(
            'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB',            'AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY'            ,'AZ'
        );
        
        // 字段从那里开始
        for ($i = 0; $i < $cellNum; $i ++) {
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '1', $expCellName[$i][1]);
        }
        // 数据从那里开始
        for ($i = 0; $i < $dataNum; $i ++) {
            for ($j = 0; $j < $cellNum; $j ++) {
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 2), $expTableData[$i][$expCellName[$j][0]]);
            }
        }
        
        header('pragma:public');
        
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls"); // attachment新窗口打印inline本窗口打印
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit();
    }
	
	//个人月积分趋势图
	public function memberChart(){
		$map['site_id']=__SITEID__;
		$integraltype = M('Integral_type') -> where($map) -> select();
		$map['member_id']=$this->_param('member_id')?$this->_param('member_id'):$this->memberInfo['id'];
		$time=$this->month();
		foreach($integraltype as $v){
			$monthlist=$this->monthlist($map['member_id'],$v['id'],$time['start'],$time['end'],['integraltypeid'=>$v['id']]);
			$montharr[$v['remark']]=$monthlist['arr'];
			$monthdate=$monthlist['date'];
			$monthform=$monthlist['monthform'];
		}
		$this->monthdate=$monthdate;
		$this->monthform=$monthform;
		$this->montharr=$montharr;
		$this->display();
	}
}
